package top.codetheory.thread._001_打断;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.LockSupport;

/**
 * @author: CodeTheory
 * @since: 2024/4/21 上午8:45
 **/
@Slf4j
public class _004_打断Park {

    public static void main(String[] args) {
//        test1();
        test2();
    }


    /** 可以看到0-park 返回的是true, 因为这里在park等待锁的时候，被打断， 所以返回true， 紧接着又重置为了false<br>
     * 后面为false，且卡主的原因是因为没有获取到锁，或者没有打断 <br>
     *<img src="https://gitee.com/codetheory/img-on1/raw/master/img01/1713661615186-2024-4-2109:06:55.png"  />
     */
    public static void test2() {
        Thread t1 = new Thread(() -> {
            Thread currentThread = Thread.currentThread();
            for (int i = 0; i < 10; i++) {
                log.info("{}-park 前...{}",i, currentThread.isInterrupted());
                LockSupport.park();  // 线程状态为 waiting
                log.info("{}-park 后...{}",i, Thread.interrupted());  // 返回当前的打断状态, 并且会清除打断状态 即为false
            }
        }, "t1");


        t1.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        t1.interrupt();

        log.info("main end");
    }


    /** 在park之前, interrupt 是 false, park 就是等 interrupt 为 true的时候才继续执行, 并且一直为true就一直会执行 <br>
     * <img src="https://gitee.com/codetheory/img-on1/raw/master/img01/1713661216665-2024-4-2109:00:17.png"  />
     */
    public static void test1() {

        Thread t1 = new Thread(() -> {
            Thread currentThread = Thread.currentThread();
            for (int i = 0; i < 10; i++) {
                log.info("{}-park 前...{}",i, currentThread.isInterrupted());
                LockSupport.park();
                log.info("{}-park 后...{}",i, currentThread.isInterrupted());
            }
        }, "t1");


        t1.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        t1.interrupt();

        log.info("main end");


    }



}